package com.notary.util;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class HtmlToPdf {
//    private static String dstImgFolder = "E:/pdf";

    //wkhtmltopdf在本机中的路径
    private static String toPdfTool = "D:\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";

    public static String h5CoverPdf(String content) {
        File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
        String dstImgFolder = desktopDir.getAbsolutePath()+"/pdf";

        if (System.getProperty("os.name").indexOf("Windows") == -1) {
            //非windows 系统
            dstImgFolder = "/opt/notary/dev/temp/banzheng";
        }
        File file = new File(dstImgFolder);

        if (!file.exists()) {
            boolean notUse = file.mkdirs();
        }

        final String fileName = IdUtil.simpleUUID(),
                htmlPath = file.getAbsolutePath() + File.separator + fileName + ".html",
                pdfPath = file.getAbsolutePath() + File.separator + fileName + ".pdf";
        try (FileOutputStream fos = new FileOutputStream(htmlPath)) {
            fos.write(content.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            log.error("H5输入异常", e);
            return null;
        }

        if (cover(htmlPath, pdfPath)) {
            return pdfPath;
        }

        return null;
    }

    private static boolean cover(String inPath, String outPath) {
        StringBuilder command = new StringBuilder();
        if (System.getProperty("os.name").indexOf("Windows") == -1) {
            //非windows 系统
            toPdfTool = "/usr/bin/wkhtmltopdf";
        }
        command.append(toPdfTool).append(" ");
        command.append("--page-size A4 ");
        command.append("--margin-right 18mm ");
        command.append("--margin-left 18mm ");
        command.append("--margin-bottom 20mm ");
        command.append("--margin-top 18mm ");
        command.append("--encoding UTF-8 ");
        command.append(inPath).append(" ");
        command.append(outPath);

        try {
            Process process = Runtime.getRuntime().exec(command.toString());
            process.waitFor();
            return true;
        } catch (IOException | InterruptedException e) {
            log.error("Webkit html to pdf error", e);
            return false;
        }

    }

}
